function searchChar({el, text, totalHeight, prefix, expandText}: ISearchChar) {
  let left = 0;
  let right = text.length;
  while (left < right) {
    let mid = left + Math.floor((right - left) / 2);
    //我当前的需求是在末尾添加省略号和“查看全文”，所以计算高度时也需要加上
    el.innerHTML = `${text.slice(0, mid)}${prefix}${expandText}`;
    let currentHeight = parseInt(getComputedStyle(el).height);
    //当前截取后的文本高度与我们所需行数高度进行对比
    if (currentHeight == totalHeight) {
      left = mid + 1;
    } else if (currentHeight > totalHeight) {
      right = mid;
    } else if (currentHeight < totalHeight) {
      left = mid + 1;
    }
  }
  return left - 1;
}

export const vCutText = {
  mounted(el: HTMLDivElement, binding: IBinding) {
    const {rows, text, prefix, spanStyle, expandText, collapseText} = binding.value;
    /**裁剪后的html */
    let cutInnerHtml = '';
    /**完整显示的html */
    let allInnerHtml = '';
    //先获取到单行情况下的高度
    el.innerHTML = 'a';
    let rowHeight = parseInt(getComputedStyle(el).height);
    //获取所需行数会显示的高度，高度可能有小数，存在浮点精点丢失，此处处理为整数
    let totalHeight = rowHeight * rows;
    //获取完整文本会显示的高度
    el.innerHTML = text;
    let allTextHeight = parseInt(getComputedStyle(el).height);
    //判断完整文本是否会超出我们所需的行数，如果超出则进行截取
    //这里需要注意的是
    //行内元素getComputedStyle(el).height获取的高度为‘auto’,会导致totalHeight为NaN，在二分查找时进入死循环，所以这里进行判断
    if (allTextHeight <= totalHeight || getComputedStyle(el).height == 'auto') {
      return;
    } else {
      let index = searchChar({el, text, totalHeight, prefix, expandText});
      cutInnerHtml = `${text.slice(0, index)}${prefix}<span class="__cut-text-btn" style="${spanStyle}">${expandText}</span>`;
      allInnerHtml = `${text}<span class="__cut-text-btn" style="${spanStyle}">${collapseText}</span>`;
      el.innerHTML = cutInnerHtml;
    }

    el.addEventListener('click', (e: any) => {
      if (e.target.className.includes('__cut-text-btn')) {
        /**如果点击了展开按钮 */
        el.innerHTML = e.target.innerHTML === expandText ? allInnerHtml : cutInnerHtml;
      }
    });
  }
};

interface IBinding {
  value: IVCutText;
}

export interface IVCutText {
  /** 行数 */
  rows: number;
  /** 文本内容 */
  text: string;
  /** 替换前缀 */
  prefix: string;
  /** span样式 */
  spanStyle: string;
  /** 展开的文案 */
  expandText: string;
  /** 裁剪的文案 */
  collapseText: string;
}

interface ISearchChar {
  el: HTMLDivElement;
  text: string;
  totalHeight: number;
  prefix: string;
  expandText: string;
}
